package io.gitee.tziye.spring;

import io.gitee.tziye.RenaiClient;
import io.gitee.tziye.core.instance.DefaultRenaiClient;
import io.gitee.tziye.core.instance.InstanceSpec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import static io.gitee.tziye.common.Constants.DEFAULT;

@EnableConfigurationProperties(value = RenaiProperties.class)
@Configuration
public class RenaiAutoConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public RenaiClient renaiClient(RenaiProperties renaiProperties) {
        if (renaiProperties == null || renaiProperties.dataSource() == null) {
            return null;
        }
        InstanceSpec instanceSpec = renaiProperties.instance();
        if (StringUtils.isBlank(renaiProperties.getService())) {
            instanceSpec.setService(environment.getProperty("spring.application.name"));
        }
        if (StringUtils.isBlank(instanceSpec.getService())) {
            instanceSpec.setService(DEFAULT);
        }
        if (renaiProperties.getPort() <= 0) {
            Integer serverPort = environment.getProperty("server.port", Integer.class);
            if (serverPort != null) {
                instanceSpec.setPort(serverPort);
            }
        }
        return new DefaultRenaiClient(renaiProperties.dataSource(), instanceSpec);
    }
}
